#!/bin/bash
#Author: YangYi
#Date: 2025-04-18
#Version: v1
#Content 一键诊断、处置原子能力，集群健康状态检测
#1. 集群检测-节点状态
#2. 集群检测-核心Pod状态
#3. 集群检测-控制平面组件健康
#4. 集群检测-API响应延迟,平均响应 <500ms


# ---------------------------初始化全局变量----------------------------

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 从kubeconfig获取token
CURRENT_CONTEXT=$(kubectl config current-context)
USER=$(kubectl config view -o jsonpath="{.contexts[?(@.name == '${CURRENT_CONTEXT}')].context.user}")
#TOKEN=$(kubectl config view -o jsonpath="{.users[?(@.name == '${USER}')].user.token}")
TOKEN=$(kubectl describe secret $(kubectl get secret | grep ^default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t' | tr -d ' ')

# 节点IP获取
#VIP=$1
VIP="10.145.216.249"
PORT="8888"

# ----------------------------功能模块函数-----------------------------


# 检查节点状态
check_nodes() {
    local api_url="http://$VIP:$PORT/api/v1/nodes"
    local response=$(curl -s -k -H "Authorization: Bearer $TOKEN" "$api_url")
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}无法连接Kubernetes API服务器${NC}"
        return 1
    fi

    # 使用jq解析节点状态
    if ! command -v jq &> /dev/null; then
        echo -e "${RED}错误：需要安装jq工具${NC}"
        exit 1
    fi
    
    echo "$response" | jq -r '.items[] | {
        ip: .status.addresses[] | select(.type == "InternalIP").address,
        status: .status.conditions[] | select(.type == "Ready").status
    } | "\(.ip) \(.status)"' | while read -r line; do
        ip=$(echo "$line" | awk '{print $1}')
        status=$(echo "$line" | awk '{print $2}')

        if [ "$status" != "True" ]; then
            echo -e "${RED}节点异常: ${ip} - 状态: ${status}${NC}"
            has_error=1
        else
            echo -e "${GREEN}节点正常: ${ip}${NC}"
        fi
    done


}

# 检查控制平面组件
check_components() {
    local errors=0
     
    # 检查controller-manager/scheduler/etcd
    local api_url="http://${VIP}:$PORT/api/v1/componentstatuses"
    local response=$(curl -k -s -H "Authorization: Bearer $TOKEN" "$api_url")


    echo "$response" | jq -r '.items[] | "\(.metadata.name) \(.conditions[0].status)"' | while read -r line; do
        component=$(echo "$line" | awk '{print $1}')
        status=$(echo "$line" | awk '{print $2}')

        if [ "$status" != "True" ]; then
            echo -e "${RED}组件异常: ${component} - 状态: ${status}${NC}"
            has_error=1
        else
            echo -e "${GREEN}组件正常: ${component}${NC}"
        fi
    done 

    return $errors
}

# 检查核心Pod状态
check_pods() {
  
    local api_url="http://${VIP}:$PORT/api/v1/pods"
    local response=$(curl -k -s -H "Authorization: Bearer $TOKEN" "$api_url")

    if [ $? -ne 0 ]; then
        echo -e "${RED}无法获取Pod信息${NC}"
        return 1
    fi

    local has_error=0
    echo "$response" | jq -r '.items[]  | "\(.metadata.name) \(.metadata.namespace) \(.status.conditions[1].status)"' | grep "kube-system" | grep "heapster\|k8s\|kube-dns\|kubernetes-dashboard\|metrics-server\|traefik-ingress-controller" | while read -r line; do
    #echo "$response" | jq -r '.items[]  | "\(.metadata.name) \(.metadata.namespace) \(.status.phase)"' | grep "ccse-api\|coredns\|migrateout" | while read -r line; do
        name=$(echo "$line" | awk '{print $1}')
        namespace=$(echo "$line" | awk '{print $2}')
        status=$(echo "$line" | awk '{print $3}')

        #if [ "$status" != "Running" ]; then
        if [ "$status" == "True" ]; then
            echo -e "${GREEN}Pod正常: ${name}${NC}"
        else
            echo -e "${RED}Pod异常: ${name}${NC}"
            has_error=1
        fi
    done

    return $has_error
 
}

# 检查API响应延迟
check_api_latency() {
    local api_url="http://$VIP:$PORT/api/v1/nodes"
    local total_time=0
    local count=5

    for ((i=0; i<count; i++)); do
        start_time=$(date +%s.%N)
        curl -s -k -o /dev/null -H "Authorization: Bearer $TOKEN" "$api_url" >/dev/null 2>&1
        end_time=$(date +%s.%N)
        duration=$(echo "$end_time - $start_time" | bc)
        total_time=$(echo "$total_time + $duration" | bc)
    done

    avg_time=$(echo "scale=3; $total_time / $count" | bc)
        echo -e "平均API响应时间: ${YELLOW}${avg_time}s${NC}"

    if (( $(echo "$avg_time < 0.5" | bc -l) )); then
        echo -e "${GREEN} API响应延迟正常${NC}"
        return 0
    else
        echo -e "${RED} API响应延迟超过500ms${NC}"
        return 1
    fi
}

# 主函数
main() {
    echo -e "\n${YELLOW}===== 开始集群状态检查 =====${NC}"
    
    echo -e "\n${YELLOW}1. 检查节点状态...${NC}"
    check_nodes || exit_code=1

    echo -e "\n${YELLOW}2. 检查控制平面组件...${NC}"
    check_components || exit_code=1

    echo -e "\n${YELLOW}3. 检查核心Pod状态...${NC}"
    check_pods || exit_code=1

    echo -e "\n${YELLOW}4. 检查API响应延迟...${NC}"
    check_api_latency || exit_code=1

    echo -e "\n${YELLOW}===== 检查完成 =====${NC}"
    exit ${exit_code:-0}
}

main
